<?php

class Press extends DirModel
{
	
	public $edition;
	
	public function getViewColumns()
	{
		return array(
			'ut_press_name',
			'format.ut_format_name',
			'paper_type.ut_paper_type_name',
		);
	}
	
	public function getUpdateFields()
	{  
		return array(
			'ut_press_name',
			array(
				'name'=>'ut_format_id',
				'editor'=>'dropDown',
				'data'=>CActiveRecord::model('Format')->listData(),
			),
			array(
				'name'=>'ut_paper_type_id',
				'editor'=>'dropDown',
				'data'=>CActiveRecord::model('PaperType')->listData(),
			),			
			'ut_press_t1_s1',
			'ut_press_t1_s2',
			'ut_press_t2_s1',
			'ut_press_t2_s2',
			'ut_press_descr',
						
		);
	}
	
	public function getColorities()
	{
		$colorities = array();
		foreach($this->colority as $colority){
			$colorities[]=$colority->ut_colority_id;
		}
		return $colorities;
	}
	
	public function setColorities($value)
	{
		if (is_array($value)){
			CActiveRecord::model('PressColority')->deleteAllByAttributes(array('ut_press_id'=>$this->ut_press_id));
			foreach ($value as $val){
				$pc = new PressColority();
				$pc->ut_press_id = $this->ut_press_id;
				$pc->ut_colority_id = $val;
				$pc->save();
			}
		}
	}

	public function getDensities()
	{
		$densities = array();
		foreach($this->density as $density){
			$densities[]=$density->ut_density_id;
		}
		return $densities;
	}
	
	public function setDensities($value)
	{
		if (is_array($value)){
			CActiveRecord::model('PressDensity')->deleteAllByAttributes(array('ut_press_id'=>$this->ut_press_id));
			foreach ($value as $val){
				$pd = new PressDensity();
				$pd->ut_press_id = $this->ut_press_id;
				$pd->ut_density_id = $val;
				$pd->save();
			}
		}
	}	
	
	public function pressEdition($calcForm)
	{
					
	}
	
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'ut_press';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('ut_press_name', 'required'),
			array('ut_format_id, ut_paper_type_id, ut_press_t1_s1, ut_press_t1_s2, ut_press_t2_s1, ut_press_t2_s2', 'numerical', 'integerOnly'=>true),
			array('ut_press_name', 'length', 'max'=>255),
			array('colorities,densities','safe'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
	//		'colority' => array(self::MANY_MANY, 'Colority', 'ut_press_colority(ut_press_id,ut_colority_id)'),
		//	'format' => array(self::MANY_MANY, 'Format', 'ut_press_format(ut_press_id,ut_format_id)'),
			//'paper' => array(self::STAT, 'Comment', 'post_id', 'condition'=>'status='.Comment::STATUS_APPROVED),
			'density' => array(self::MANY_MANY, 'Density', 'ut_press_density(ut_press_id,ut_density_id)','with'=>'paper'),
			'format' => array(self::BELONGS_TO, 'Format', 'ut_format_id'),
			'paper_type' => array(self::BELONGS_TO, 'PaperType', 'ut_paper_type_id'),
			'press_resource' => array(self::HAS_MANY, 'PressResource', 'ut_press_id','with'=>'resource'),
			'paper_expense' => array(self::HAS_ONE, 'PaperExpense', 'ut_press_id','with'=>array('base_format','format'),'order'=>'ut_exp_edition DESC','condition'=>'ut_exp_edition<'.$this->edition),
			'press_calcrow' => array(self::HAS_MANY, 'PressCalcrow', 'ut_press_id','order'=>'calcrow.ut_calcrow_order','with'=>'calcrow'),
		);
	}
	
	public function scopes()
	{
		return array(
			'newspaper'=>array(
				'condition'=>'newspaper=1',
			),
		);
	}
	
	
	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'ut_press_id' => 'Id',
			'ut_press_name' => 'Name',
			'ut_format_id' => 'Формат',
			'frequency' => 'Frequency',
		);
	}
	
	public function calcParams()
	{		
		$data = Yii::app()->db->createCommand('SELECT param_name, param_value FROM ut_calc_params')->queryAll();
		$calcParams = new CMap();
		foreach($data as $row){
			$calcParams[$row['param_name']] = $row['param_value'];
		}
		return $calcParams;
	}

	public function getCalcSum()
	{
		return Yii::app()->db->createCommand('SELECT uc.ut_calc_sum FROM ut_calc uc WHERE uc.ut_press_id = :press AND uc.id = :session AND uc.ut_calcrow_id=14')->queryScalar(array('press'=>$this->ut_press_id,'session'=>Yii::app()->session->sessionId));
	} 

	public function getCalcDensity()
	{
		return Yii::app()->db->createCommand('SELECT uc.ut_calc_sum FROM ut_calc uc WHERE uc.ut_press_id = :press AND uc.id = :session AND uc.ut_calcrow_id=32')->queryScalar(array('press'=>$this->ut_press_id,'session'=>Yii::app()->session->sessionId));
	} 
	
	public function groupSum($group)
	{
		return Yii::app()->db->createCommand('SELECT sum(uc.ut_calc_sum)FROM  ut_calc uc JOIN ut_calcrow ucc ON ucc.ut_calcrow_id = uc.ut_calcrow_id JOIN ut_calcrow_group ucg on ucg.ut_group_id=ucc.ut_group_id WHERE uc.ut_press_id = :press AND uc.id = :session AND ucg.ut_group_name = :group')->queryScalar(array('press'=>$this->ut_press_id,'session'=>Yii::app()->session->sessionId,'group'=>$group));
	} 
	
	public function calcResult()
	{
		$calc = CActiveRecord::model('UtCalc')->with('calcrow','calcrow.group','press')->findAll(
			't.ut_press_id = :press AND t.id = :session',
			array('press'=>$this->ut_press_id,'session'=>Yii::app()->session->sessionId)
		);
		
		$dataProvider=new CArrayDataProvider($calc, array(
				'keyField'=>'ut_calcrow_id',
				'pagination'=>false,//array(
				//'pageSize'=>10,
		//	),
		));		
		return $dataProvider;
	} 	
	
	public function findCanPrint($calcForm)
	{
		return $this->findAllBySql(
"
SELECT DISTINCT up.* 
  FROM ut_press up
  JOIN ut_press_paper upp ON upp.ut_press_id = up.ut_press_id 
  JOIN ut_paper upr ON upr.ut_paper_id=upp.ut_paper_id AND upr.ut_density_id=:density AND upr.ut_paper_kind_id = :paperKind
	JOIN ut_press_paper_colority upc ON upc.ut_paper_id = upp.ut_paper_id AND upc.ut_press_id=upp.ut_press_id AND upc.ut_colority_id=:colority  
  JOIN ut_format uf ON uf.ut_format_id = up.ut_format_id AND uf.ut_format_height>=:height AND uf.ut_format_width>=:width
"		, 
			array(
				'density'=>$calcForm->density,
				'paperKind'=>$calcForm->paperKind,
				'colority'=>$calcForm->colority,
				'height'=>$calcForm->formatHeight,
				'width'=>$calcForm->formatWidth,
		));
	}
	public function calcNewspaper()
	{
		
	}
	
	public function calcPress($calcForm)
	{
		$calcParams = $this->calcParams();
		CActiveRecord::model('UtCalc')->deleteAllByAttributes(array('ut_press_id'=>$this->ut_press_id));
		if($this->press_calcrow){
			foreach($this->press_calcrow as $pressCalcrow){
				$calc1 = new UtCalc();
				$calc1->id = Yii::app()->session->sessionId;
				$calc1->ut_calcrow_id = $pressCalcrow->ut_calcrow_id;
				$calc1->ut_press_id = $pressCalcrow->ut_press_id;
				$formula =  $pressCalcrow->ut_calc_formula;
				if (empty($formula))
					$formula = $pressCalcrow->calcrow->ut_calcrow_formula;
				if (!empty($formula)){
					$formula = strtr($formula,$calcParams->toArray());
					$error = $this->evalExpression($formula,array(
						'press'=>$this, 
						'row'=>$calc1,
						'calcForm'=>$calcForm, 
						'calcrow'=>$pressCalcrow,
						'calcParams'=>$calcParams
					));
					$calc1->ut_debug = $formula;
					if (!empty($error))
						$calc1->ut_calc_error = $error;
					$calcParams[$pressCalcrow->calcrow->ut_calcrow_name] = $calc1->ut_calc_sum;
				}
				$calc1->save();
			}
		}
	}
	
	public function evalExpression($_expression_,$_data_=array())
	{
		extract($_data_);
		ob_start();
    eval($_expression_);
    $result = ob_get_contents();
    ob_end_clean();
		return $result;
	}
	
}